<?php
class Bootstrap{

	/**
	 * from application.ini
	 */
	protected $_config = array();

	/**
	 * app
	 */
	protected $_app;

	/**
	 * module name
	 */
	protected $_module;

	/**
	 * action name
	 */
	protected $_action;

	/**
	 * @params app
	 */
	public function __construct( $app ){
		$this->_app = $app;
		$this->_config = $app->_config;
	}

	/**
	 * to be continue....
	 */
	private function getRequest(){
		if(isset($_GET['action'])){
			$this->_action = $_GET['action'];
		}else{
			$this->_action = $this->_config['application']['defaultAction'];
		}

		if(isset($_GET['module'])){
			$this->_module = $_GET['module'];
		}else{
			$this->_module = $this->_config['application']['defaultModule'];
		}
	}

	public function getModule($module){
		$this->_module = strtolower($module);
	}
	
	public function getAction($action){
		$this->_action = strtolower($action);
	}

	/**
	 * to be continue....
	 */
	public function dispatch(){

		$this->getRequest();
		$this->getModule($this->_module);
		$this->getAction($this->_action);

		$module = ucfirst($this->_module)."Controller";

		set_exception_handler(array('Error', 'exceptionHandler'));	

		if( file_exists( dirname(__FILE__).'/'.$this->_config['application']['controllers']."/".$module.".php" ) ){
			require_once $this->_config['application']['controllers']."/".$module.".php";

			Controller::init( $this->_config, $this->render() );
			$class = new $module();
			@call_user_func( array($class, $this->_action));
		}else{
			require_once "lib/CException.php";
			throw new CException("page not found", 404);
		}
	}

	/**
	 * render view
	 * to be continue.....
	 */
	public function render($file=null){
		$view = $this->_config['application']['views'];
		$view = $view."/".$this->_module;
		$view = $view."/".$this->_action.".".$this->_config['application']['viewExt'];
		return $view;
	}

	public function run(){
		$this->dispatch();
	}
}
